import 'package:edu/constants/app_strings.dart';
import 'package:edu/pages/course/course_detail/video_player/course_video_player_widget_logic.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:tuple/tuple.dart';
import 'package:video_player/video_player.dart';

class CourseVideoPlayerWidget extends StatefulWidget {
  const CourseVideoPlayerWidget({super.key});

  @override
  State<CourseVideoPlayerWidget> createState() =>
      _CourseVideoPlayerWidgetState();
}

class _CourseVideoPlayerWidgetState extends State<CourseVideoPlayerWidget> {
  @override
  void initState() {
    super.initState();
    context.read<CourseVideoPlayerWidgetLogic>().init();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Selector<CourseVideoPlayerWidgetLogic, Tuple2<bool, bool>>(
        selector: (context, logic) =>
            Tuple2(logic.videoController.value.isInitialized, logic.error),
        builder: (context, v, child) {
          if (v.item1) {
            return _buildVideoWidget(context);
          } else {
            if (v.item2) {
              final errorColor = Theme.of(context).colorScheme.error;
              return Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: 20,
                  vertical: 10,
                ),
                decoration: BoxDecoration(
                  color: Theme.of(context).colorScheme.surface,
                  borderRadius: BorderRadius.circular(10),
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Icon(Icons.error, color: errorColor, size: 40),
                    const SizedBox(height: 10),
                    Text(
                      AppStrings.videoLoadError,
                      style: Theme.of(
                        context,
                      ).textTheme.bodyLarge?.copyWith(color: errorColor),
                    ),
                  ],
                ),
              );
            } else {
              return const CircularProgressIndicator();
            }
          }
        },
      ),
    );
  }

  Widget _buildVideoWidget(BuildContext context) {
    final logic = context.read<CourseVideoPlayerWidgetLogic>();
    return Stack(
      children: [
        AspectRatio(
          aspectRatio: logic.videoController.value.aspectRatio,
          child: VideoPlayer(logic.videoController),
        ),
        Positioned(
          bottom: 0,
          left: 0,
          right: 0,
          child: _buildVideoControlBar(context),
        ),
      ],
    );
  }

  Widget _buildVideoControlBar(BuildContext context) {
    return Container(
      color: Colors.black26,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          const SizedBox(width: 5),
          SizedBox(
            width: 30,
            height: 30,
            child: IconButton(
              icon: Selector<CourseVideoPlayerWidgetLogic, bool>(
                selector: (context, logic) =>
                    logic.videoController.value.isPlaying,
                builder: (context, v, child) {
                  return Icon(
                    v ? Icons.pause : Icons.play_arrow,
                    color: Colors.white,
                    size: 20,
                  );
                },
              ),
              padding: const EdgeInsets.all(0),
              onPressed: () {
                final logic = context.read<CourseVideoPlayerWidgetLogic>();
                if (logic.videoController.value.isPlaying) {
                  logic.videoController.pause();
                } else {
                  logic.videoController.play();
                }
              },
            ),
          ),
          const SizedBox(width: 5),
          Expanded(
            child: SizedBox(
              height: 30,
              child: Column(
                children: [
                  const Spacer(),
                  VideoProgressIndicator(
                    context
                        .read<CourseVideoPlayerWidgetLogic>()
                        .videoController,
                    allowScrubbing: true,
                    colors: const VideoProgressColors(
                      playedColor: Colors.white,
                      backgroundColor: Colors.grey,
                      bufferedColor: Colors.lightGreen,
                    ),
                  ),
                  const SizedBox(height: 5),
                  const Spacer(),
                ],
              ),
            ),
          ),
          const SizedBox(width: 15),
          SizedBox(
            width: 45,
            child: Selector<CourseVideoPlayerWidgetLogic, Duration>(
              selector: (context, logic) {
                final value = logic.videoController.value;
                return value.duration - value.position;
              },
              builder: (context, v, child) {
                return Text(
                  '${v.inMinutes}:${(v.inSeconds % 60).toString().padLeft(2, '0')}',
                  style: const TextStyle(
                    fontFamily: 'Courier',
                    fontWeight: FontWeight.bold,
                    fontSize: 14,
                    color: Colors.white,
                  ),
                  textAlign: TextAlign.right,
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}
